from django.views.generic import DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from .models import PetDevice, LocationLog, SafeZone
from django.shortcuts import get_object_or_404
import folium
from django.http import JsonResponse
from django.utils import timezone
from datetime import timedelta


class PetTrackingView(LoginRequiredMixin, DetailView):
    model = Pet
    template_name = 'tracking/map.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pet = self.object

        # 获取设备
        device = get_object_or_404(PetDevice, pet=pet)

        # 获取最新位置
        latest_location = LocationLog.objects.filter(device=device).order_by('-timestamp').first()

        if latest_location:
            # 创建地图
            m = folium.Map(
                location=[latest_location.location.y, latest_location.location.x],
                zoom_start=15,
                tiles='OpenStreetMap'
            )

            # 添加当前位置标记
            folium.Marker(
                [latest_location.location.y, latest_location.location.x],
                popup=f"{pet.name} - {latest_location.timestamp.strftime('%Y-%m-%d %H:%M')}",
                icon=folium.Icon(color='green', icon='paw', prefix='fa')
            ).add_to(m)

            # 添加安全区域
            for zone in SafeZone.objects.filter(pet=pet, is_active=True):
                folium.GeoJson(
                    zone.area,
                    name=zone.name,
                    style_function=lambda x: {'fillColor': 'green' if zone.is_active else 'gray'}
                ).add_to(m)

            # 添加最近24小时的轨迹
            twenty_four_hours_ago = timezone.now() - timedelta(hours=24)
            path_points = LocationLog.objects.filter(
                device=device,
                timestamp__gte=twenty_four_hours_ago
            ).order_by('timestamp')

            if path_points.count() > 1:
                folium.PolyLine(
                    [(p.location.y, p.location.x) for p in path_points],
                    color='blue',
                    weight=2.5,
                    opacity=1
                ).add_to(m)

            context['map'] = m._repr_html_()

        context['device'] = device
        context['api_key'] = settings.MAPBOX_ACCESS_KEY
        return context


def current_location(request, pet_id):
    pet = get_object_or_404(Pet, id=pet_id, owner=request.user)
    device = get_object_or_404(PetDevice, pet=pet)
    location = LocationLog.objects.filter(device=device).order_by('-timestamp').first()

    if location:
        return JsonResponse({
            'lat': location.location.y,
            'lng': location.location.x,
            'timestamp': location.timestamp.isoformat(),
            'battery': device.battery_level
        })
    return JsonResponse({'error': 'No location data'}, status=404)